#!/usr/bin/python3

import shutil
import sys
from random import shuffle

from PyQt5 import QtWidgets
from PyQt5.QtCore import Qt, QFile, QTextStream
from PyQt5.QtGui import QPixmap, QIcon, QCursor
from PyQt5.QtWidgets import QMainWindow, QLabel, QGridLayout, QWidget, QPushButton, QFileDialog, QGroupBox, QComboBox, \
    QSizePolicy, QHBoxLayout, QVBoxLayout, QFrame, QMenu

from rublev_get_icons import get_icons
from rublev_palette import Palette
from rublev_screenshots import ForScreenShot


class MainWindow(QMainWindow):
    def change_theme(self):
        self.color_index = (self.color_index + 1) % 2
        file = QFile(self.style_files[self.color_index])
        file.open(QFile.ReadOnly | QFile.Text)
        stream = QTextStream(file)
        app.setStyleSheet(stream.readAll())
        self.menu_list_box.clear()
        if self.color_index == 0:
            self.menu_list_box.addItems([i.split('/')[-1].capitalize() for i in self.dark_keys])
        else:
            self.menu_list_box.addItems([i.split('/')[-1].capitalize() for i in self.light_keys])
        self.change_other_icons()

    def make_screenshot(self):
        self.new_widget = ForScreenShot(self)
        self.new_widget.app = app
        self.new_widget.setWindowTitle(self.current_icon_name)
        central_widget_for_new_widget = QWidget()
        screenshot_layout = QGridLayout()
        central_widget_for_new_widget.setLayout(screenshot_layout)

        sizes = (8, 16, 22, 32, 48, 64, 128)
        light_icons = QGroupBox()
        light_icons_layout = QGridLayout()
        light_icons.setLayout(light_icons_layout)
        dark_icons = QGroupBox()
        dark_icons_layout = QGridLayout()
        dark_icons.setLayout(dark_icons_layout)
        light_icons.setObjectName('light_icons')
        dark_icons.setObjectName('dark_icons')

        for i in range(len(sizes)):
            for layout in (light_icons_layout, dark_icons_layout):
                img = QLabel()
                img.setPixmap(QPixmap(self.current_icon_name).scaled(sizes[i], sizes[i]))
                img.setAlignment(Qt.AlignCenter)
                layout.addWidget(img, 0, i)
                layout.addWidget(img, 0, i)
                label = QLabel(str(sizes[i]))
                label.setAlignment(Qt.AlignCenter)
                layout.addWidget(label, 1, i)
                layout.addWidget(label, 1, i)

        screenshot_layout.addWidget(light_icons, 0, 0)
        screenshot_layout.addWidget(dark_icons, 1, 0)

        file = QFile(self.style_files[1])
        file.open(QFile.ReadOnly | QFile.Text)
        stream = QTextStream(file)
        light_icons.setStyleSheet(stream.readAll())
        file = QFile(self.style_files[0])
        file.open(QFile.ReadOnly | QFile.Text)
        stream = QTextStream(file)
        dark_icons.setStyleSheet(stream.readAll())

        self.new_widget.setCentralWidget(central_widget_for_new_widget)
        self.new_widget.show()

    def open_icon(self):
        file, ok = QFileDialog.getOpenFileName(None, "Выберите значок", "", "Svg files (*.svg)")
        if ok:
            self.icons_groupbox_layout.itemAtPosition(1, 1).widget().setParent(None)
            new_icon_label = QLabel()
            new_icon_label.setAlignment(Qt.AlignCenter)
            new_icon_label.setAlignment(Qt.AlignCenter)
            new_icon_label.setPixmap(QPixmap(file).scaled(48, 48))
            self.icons_groupbox_layout.addWidget(new_icon_label, 1, 1)
            img = QLabel()
            img.setAlignment(Qt.AlignCenter)
            img.setPixmap(QPixmap(file).scaled(128, 128))
            self.icon_sizes_groupbox_layout.itemAtPosition(0, 0).widget().setParent(None)
            self.icon_sizes_groupbox_layout.addWidget(img, 0, 0, 1, len(self.sizes))
            for column in range(len(self.sizes)):
                img = QLabel()
                img.setAlignment(Qt.AlignCenter)
                img.setPixmap(QPixmap(file).scaled(self.sizes[column], self.sizes[column]))
                self.icon_sizes_groupbox_layout.itemAtPosition(2, column).widget().setParent(None)
                self.icon_sizes_groupbox_layout.addWidget(img, 2, column)
            self.current_icon_name = file
            self.icon_sizes_groupbox.setTitle(file.split('/')[-1])

    def create_icon(self):
        self.context_menu = QMenu(self.create_icon_button)
        action1 = self.context_menu.addAction("Inkscape (*.svg)")
        action2 = self.context_menu.addAction("Figma (*.fig)")
        # action3 = self.context_menu.addAction("Sketch (*.sk)")

        action1.triggered.connect(self.save_icon)
        action2.triggered.connect(self.save_icon)
        # action3.triggered.connect(self.save_icon)
        self.context_menu.popup(QCursor.pos())

    def save_icon(self):
        file, filter = QFileDialog.getSaveFileName(self, "Выберите шаблон и папку", '.',
                                                   self.sender().text())
        if filter:
            # for ext in ('svg', 'fig', 'sk'):
            for ext in ('svg', 'fig'):
                if ext in filter:
                    if not file.endswith(ext):
                        file += '.' + ext
                    shutil.copyfile(f'Rublev icon template.{ext}', file)

    def test_in_system(self):
        self.setWindowIcon(QIcon(self.current_icon_name))

    def open_palette(self):
        palette = Palette(self)
        palette.app = app
        palette.show()

    def change_other_icons(self):
        self.icons_group_index = self.menu_list_box.currentIndex()
        for row in range(3):
            for column in range(3):
                if row != 1 or column != 1:
                    self.icons_groupbox_layout.itemAtPosition(row, column).widget().setParent(None)
        if self.color_index == 0: # Dark
            self.current_icons = self.icons['Dark'][self.dark_keys[self.icons_group_index]].copy()
            for i in range(len(self.current_icons)):
                self.current_icons[i] = self.dark_keys[self.icons_group_index] + self.current_icons[i]
        else:
            self.current_icons = self.icons['Light'][self.light_keys[self.icons_group_index]].copy()
            for i in range(len(self.current_icons)):
                self.current_icons[i] = self.light_keys[self.icons_group_index] + self.current_icons[i]
        shuffle(self.current_icons)
        for row in range(3):
            for column in range(3):
                img = QLabel()
                img.setAlignment(Qt.AlignCenter)
                img.setPixmap(QPixmap(f'{self.current_icons[row * 3 + column]}').scaled(48, 48))
                if row != 1 or column != 1:
                    self.icons_groupbox_layout.addWidget(img, row, column)

    def __init__(self):
        QMainWindow.__init__(self)

        self.current_icon_name = "rublev.svg"
        self.setWindowTitle("Rublev")
        # self.setWindowIcon(QIcon(self.current_icon_name))
        self.setWindowIcon(QIcon('rublev.svg'))
        self.color_index = 1
        self.style_files = ('darkstyle.qss', 'lightstyle.qss')

        central_widget = QWidget(self)
        self.setCentralWidget(central_widget)

        self.grid_layout = QVBoxLayout()
        central_widget.setLayout(self.grid_layout)

        self.icons = get_icons()
        self.dark_keys = list(self.icons['Dark'].keys())
        self.light_keys = list(self.icons['Light'].keys())

        self.current_icons = [self.dark_keys[0] + fname for fname in self.icons['Dark'][self.dark_keys[0]]]
        # self.current_icons = os.listdir('/usr/share/icons/breeze-dark/mimetypes/64/')

        self.grid_layout.setSpacing(0)
        self.grid_layout.setContentsMargins(0, 0, 0, 0)

        self.first_row = QHBoxLayout()

        self.menu_list_box = QComboBox()
        self.menu_list_box.addItems([i.split('/')[-1].capitalize() for i in self.dark_keys])
        self.icons_group_index = 0
        self.menu_list_box.currentIndexChanged.connect(self.change_other_icons)
        self.first_row.addWidget(self.menu_list_box)

        open_icon_btn = QPushButton('Open Icon')
        open_icon_btn.clicked.connect(self.open_icon)
        self.first_row.addWidget(open_icon_btn)

        self.first_row.addStretch()
        # self.grid_layout.itemAtPosition(0, 2).setFixedWidth(200)

        self.create_icon_button = QPushButton('Create icon')
        self.create_icon_button.clicked.connect(self.create_icon)
        self.first_row.addWidget(self.create_icon_button)

        open_palette_btn = QPushButton('Open Color Palette')
        open_palette_btn.clicked.connect(self.open_palette)
        self.first_row.addWidget(open_palette_btn)

        first_row_widget = QWidget()
        first_row_widget.setLayout(self.first_row)
        first_row_widget.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Fixed)
        self.grid_layout.addWidget(first_row_widget)

        line = QFrame()
        line.setFrameShape(QFrame.HLine)
        line.setFrameShadow(QFrame.Sunken)
        line.setLineWidth(1)
        self.grid_layout.addWidget(line, Qt.AlignCenter)

        self.icons_groupbox = QGroupBox()
        self.icons_groupbox.setObjectName('icons_groupbox')
        self.icons_groupbox_layout = QGridLayout()

        for row in range(3):
            for column in range(3):
                img = QLabel()
                img.setAlignment(Qt.AlignCenter)
                img.setPixmap(QPixmap(f'{self.current_icons[row * 3 + column]}').scaled(48, 48))
                if row != 1 or column != 1:
                    self.icons_groupbox_layout.addWidget(img, row, column)
        new_icon_label = QLabel()
        new_icon_label.setAlignment(Qt.AlignCenter)
        new_icon_label.setPixmap(QPixmap(self.current_icon_name).scaled(48, 48))

        self.icons_groupbox_layout.addWidget(new_icon_label, 1, 1)

        self.icons_groupbox.setLayout(self.icons_groupbox_layout)
        self.icons_groupbox.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)

        self.second_row = QWidget()
        self.second_row_layout = QHBoxLayout()
        self.second_row.setLayout(self.second_row_layout)

        self.first_col = QWidget()
        self.first_col_layout = QVBoxLayout()
        self.first_col.setLayout(self.first_col_layout)
        self.second_col = QWidget()
        self.second_col_layout = QVBoxLayout()
        self.second_col.setLayout(self.second_col_layout)

        self.first_col_layout.addWidget(self.icons_groupbox)

        self.icon_sizes_groupbox = QGroupBox(self.current_icon_name)
        self.icon_sizes_groupbox_layout = QGridLayout()

        self.sizes = (8, 16, 22, 32, 48, 64)
        img = QLabel()
        img.setPixmap(QPixmap(self.current_icon_name).scaled(128, 128))
        img.setAlignment(Qt.AlignCenter)
        self.icon_sizes_groupbox_layout.addWidget(img, 0, 0, 1, len(self.sizes))
        label = QLabel('128')
        label.setAlignment(Qt.AlignCenter)
        self.icon_sizes_groupbox_layout.addWidget(label, 1, 0, 1, len(self.sizes))

        for column in range(len(self.sizes)):
            img = QLabel()
            img.setPixmap(QPixmap(self.current_icon_name).scaled(self.sizes[column], self.sizes[column]))
            img.setAlignment(Qt.AlignCenter)
            self.icon_sizes_groupbox_layout.addWidget(img, 2, column)
            label = QLabel(str(self.sizes[column]))
            label.setAlignment(Qt.AlignCenter)
            self.icon_sizes_groupbox_layout.addWidget(label, 3, column)

        self.icon_sizes_groupbox.setLayout(self.icon_sizes_groupbox_layout)
        self.icon_sizes_groupbox.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.second_col_layout.addWidget(self.icon_sizes_groupbox)
        self.first_col_layout.itemAt(0).setAlignment(Qt.AlignCenter)
        self.second_col_layout.itemAt(0).setAlignment(Qt.AlignCenter)

        self.grid_layout.addWidget(self.second_row)

        self.last_row_left_layout = QHBoxLayout()

        switch_color_btn = QPushButton('Change Theme')
        switch_color_btn.clicked.connect(self.change_theme)
        self.last_row_left_layout.addWidget(switch_color_btn)
        self.last_row_left_layout.addStretch()
        last_row_left_widget = QWidget()
        last_row_left_widget.setLayout(self.last_row_left_layout)
        last_row_left_widget.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        self.first_col_layout.addWidget(last_row_left_widget, Qt.AlignBottom)

        self.last_row_right_layout = QHBoxLayout()

        screenshot_btn = QPushButton('Screenshot')
        screenshot_btn.clicked.connect(self.make_screenshot)
        self.last_row_right_layout.addWidget(screenshot_btn)

        self.last_row_right_layout.addStretch()

        test_in_system_btn = QPushButton('Test in system')
        test_in_system_btn.clicked.connect(self.test_in_system)
        self.last_row_right_layout.addWidget(test_in_system_btn)

        last_row_right_widget = QWidget()
        last_row_right_widget.setLayout(self.last_row_right_layout)
        last_row_right_widget.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        self.second_col_layout.addWidget(last_row_right_widget)

        self.second_row_layout.addWidget(self.first_col)
        self.second_row_layout.addWidget(self.second_col)

        self.second_row_layout.setContentsMargins(0, 0, 0, 0)
        self.grid_layout.addWidget(self.second_row)

        self.change_theme()
        app.setStyle('Breeze')
        self.setMinimumHeight(400)
        self.setMinimumWidth(500)
        # first_row_widget.setStyleSheet('background: #d9d9d9;')
        # self.second_col.setStyleSheet('background: #d9d9d9;')


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    mw = MainWindow()
    mw.show()
    sys.exit(app.exec())
